package com.org.devg.monitor.server.components.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.org.devg.monitor.common.MonitorMessage;
import org.devgframwork.es5.elasticserach.EsSearch;
import com.org.devg.monitor.common.Common;
import com.org.devg.monitor.common.CommonEnum;
import com.org.devg.monitor.server.api.service.WeChatMessageService;
import com.org.devg.monitor.server.model.MonitorMessageDO;
import com.org.devg.monitor.server.model.MonitorMessageProperties;
import com.org.devg.monitor.server.model.MonitorServerConfig;
import org.devgframwork.platform.utils.CommonUtil;
import org.devgframwork.platform.utils.LocalDateUtil;
import org.devgframwork.rabbitmq.DevgRabbitAutoConfiguration;
import org.devgframwork.rabbitmq.RabbitConsumer;
import org.devgframwork.rabbitmq.RabbitConsumerTag;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Description
 * @auther dh
 * @date 2022/4/14 9:28
 */

@Slf4j
@Component
@RabbitConsumerTag(exchangeName = Common.exchangeName, queueName = Common.messageRouteKey, routeKey = Common.messageRouteKey, prefetchCount = 5, retryCount = 1)
public class RabbitMonitorConsumer extends RabbitConsumer<MonitorMessage> {

    @Resource
    private WeChatMessageService weChatMessageService;

    @Resource
    private MonitorServerConfig monitorServerConfig;

    @Override
    public void messageHander(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, MonitorMessage message) throws IOException {
        try {
            String messageStr = DevgRabbitAutoConfiguration.getObjectMapper().writeValueAsString(message);
            log.info("monitor_message_consumer:{}", messageStr);
            MonitorMessageDO monitorMessage = DevgRabbitAutoConfiguration.getObjectMapper().readValue(messageStr, MonitorMessageDO.class);
            if (null != monitorMessage.getRequestParams() && !monitorMessage.getRequestParams().isEmpty()) {
                monitorMessage.setReqParams(JSONObject.toJSONString(monitorMessage.getRequestParams()));
            }
            String startTime = monitorMessage.getStartTime();
            if (!CommonUtil.isNullOrEmpty(startTime)) {
                LocalDateTime reqLocalDateTime = LocalDateUtil.localDateTimeParse(startTime, LocalDateUtil.FORMAT_PATTERN1);
                Date reqLocalDate = LocalDateUtil.localDateTimeToDate(reqLocalDateTime);
                long reqTime = reqLocalDate.getTime();
                monitorMessage.setReqTime(reqTime);
            }
            int messageType = monitorMessage.getMessageType();
            MonitorMessageProperties monitorMessageProperties = getMonitorMessageProperties(monitorMessage.getEvnName(), monitorMessage.getModelName());
            String resultType = monitorMessage.getResultType();
            if (null != resultType && resultType.equals(CommonEnum.resultType.ERROR.getKey()) && null != monitorMessageProperties && monitorMessageProperties.getMessageError()
                    && (messageType == CommonEnum.messageType.MsgController.getKey() || messageType == CommonEnum.messageType.MsgMapper.getKey())) {
                // 发送消息
                String wechatMsg = "类名方法:" + monitorMessage.getClassMethod() + "请求错误," + "消息KEY:" + monitorMessage.getMessageKey() + ",请求时间:" + startTime + ",环境:" + monitorMessage.getEvnName();
                weChatMessageService.sendText(wechatMsg);
            }
            Long maxCostTime = (monitorMessageProperties == null ? null : monitorMessageProperties.getMessageMaxCostTime());
            Boolean messageOvertime = (monitorMessageProperties == null ? false : monitorMessageProperties.getMessageOvertime());
            Long costTime = monitorMessage.getCostTime();
            if (messageOvertime && null != maxCostTime && null != costTime && costTime > maxCostTime
                    && (messageType == CommonEnum.messageType.MsgController.getKey() || messageType == CommonEnum.messageType.MsgMapper.getKey())) {
                String wechatMsg = "类名方法:" + monitorMessage.getClassMethod() + "请求超时," + "消息KEY:" + monitorMessage.getMessageKey() + ",花费时长:" + costTime + ",请求时间:" + startTime + ",环境:" + monitorMessage.getEvnName();
                weChatMessageService.sendText(wechatMsg);
            }
            // 写入ES
            String nowDate = LocalDateUtil.localDateFormat(LocalDate.now(), LocalDateUtil.FORMAT_PATTERN4);
            String indexName = Common.messageRouteKey + "_" + nowDate;
            EsSearch.updateIndexDoc(indexName, Common.messageRouteKey, monitorMessage);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    private MonitorMessageProperties getMonitorMessageProperties(String evnName, String modelName) {

        if (null == monitorServerConfig || null == monitorServerConfig.getMonitorMessageList() || monitorServerConfig.getMonitorMessageList().size() <= 0) {
            return null;
        }
        for (MonitorMessageProperties monitorMessageProperties : monitorServerConfig.getMonitorMessageList()) {
            if (CommonUtil.equals(monitorMessageProperties.getEvnName(), evnName) && CommonUtil.equals(monitorMessageProperties.getModelName(), modelName)) {
                return monitorMessageProperties;
            }
        }
        return null;
    }
}
